//
//  LELongSQLGenerator.m
//  CreditAddressBook
//
//  Created by Lee on 15/10/15.
//  Copyright © 2015年 Lee. All rights reserved.
//

#import "LELongSQLGenerator.h"

NSString *const recordID = @"id";
static NSString *createTime = @"create_time";//记录创建日期

@implementation LELongSQLGenerator

+ (void)generateSQLForInserting:(NSDictionary *)attributes tableName:(NSString *)tableName completion:(void (^) (NSString *sql, NSArray *arguments))completion {
    if (!attributes) {
        return completion(nil, nil);
    }
    if (!attributes[recordID]) {
        //必须有id字段
        return completion(nil, nil);
    }
    
    NSMutableArray *columns = [[NSMutableArray alloc] init];
    NSMutableArray *bindingMark = [[NSMutableArray alloc] init];
    NSMutableArray *arguments = [[NSMutableArray alloc] init];
    
    NSArray *keys = attributes.allKeys;
    for (NSString *key in keys) {
        if (attributes[key]) {
            [columns addObject:key];
            if ([key isEqualToString:createTime]) {
                [arguments addObject:@((int)[[NSDate date] timeIntervalSince1970])];
            } else {
                [arguments addObject:attributes[key]];
            }
            [bindingMark addObject:@"?"];
        }
    }
    
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@ (%@) VALUES (%@)", tableName, [columns componentsJoinedByString:@","], [bindingMark componentsJoinedByString:@","]];
    completion(sql, arguments);
}

+ (void)generateSQLForUpdating:(NSDictionary *)attributes tableName:(NSString *)tableName completion:(void (^)(NSString *sql, NSArray *arguments))completion {
    if (!attributes) {
        return completion(nil, nil);
    }
    if (!attributes[recordID]) {
        //必须有id字段
        return completion(nil, nil);
    }
    
    NSMutableArray *columns = [[NSMutableArray alloc] init];
    NSMutableArray *arguments = [[NSMutableArray alloc] init];
    
    NSArray *keys = attributes.allKeys;
    for (NSString *key in keys) {
        if (attributes[key]) {
            [columns addObject:key];
            [arguments addObject:attributes[key]];
        }
    }
    
    NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET %@ WHERE id = %@", tableName, [columns componentsJoinedByString:@","], attributes[recordID]];
    completion(sql, arguments);
}
@end
